package com.aco.party.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by WangShijun on 2015/8/11.
 */
public class MailUtil {
    private static String mail_smtp_host = ConfigResource.getSystemProperty("mail_smtp_host");
    private static String mail_smtp_port = ConfigResource.getSystemProperty("mail_smtp_port");
    private static String mail_transport_protocol = ConfigResource.getSystemProperty("mail_transport_protocol");
    private static String mail_from = ConfigResource.getSystemProperty("mail_from");
    private static String mail_usr = ConfigResource.getSystemProperty("mail_usr");
    private static String mail_pwd = ConfigResource.getSystemProperty("mail_pwd");

    public static void sendMail(String mailTo, String subject, String content) {
        Properties props = System.getProperties();
        props.put("mail.debug", "false");
        props.put("mail.smtp.host", mail_smtp_host);
        props.put("mail.smtp.port", mail_smtp_port);
        props.put("mail.transport.protocol", mail_transport_protocol);
        props.put("mail.smtp.auth", "true");

        SmtpAuth sa = new SmtpAuth();
        sa.setuser(mail_usr, mail_pwd);
        Session session = Session.getDefaultInstance(props, sa);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(mail_from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));
            message.setSubject(subject);
            message.setContent(content, "text/html;charset=utf-8");
            Transport.send(message);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class SmtpAuth extends Authenticator {
    private String username;
    private String password;

    public void setuser(String username, String password) {
        this.username = username;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
}
